package com.hc.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hc.common.constant.WareConstant;
import com.hc.mall.ware.entity.PurchaseDetailEntity;
import com.hc.mall.ware.service.PurchaseDetailService;
import com.hc.mall.ware.service.WareSkuService;
import com.hc.mall.ware.vo.MergoVo;
import com.hc.mall.ware.vo.PurchaseDoneVo;
import com.hc.mall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.utils.PageUtils;
import com.hc.common.utils.Query;

import com.hc.mall.ware.dao.PurchaseDao;
import com.hc.mall.ware.entity.PurchaseEntity;
import com.hc.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>()
                        .eq(PurchaseEntity::getStatus,0)
                        .or().eq(PurchaseEntity::getStatus,1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergoVo mergoVo) {
        Long purchaseId = mergoVo.getPurchaseId();
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            Date date = new Date();
            purchaseEntity.setCreateTime(date);
            purchaseEntity.setUpdateTime(date);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        PurchaseEntity current = getById(purchaseId);
        if(!(current.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || current.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())){
            throw new RuntimeException("采购需求合并失败");
        }
        List<Long> items = mergoVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //1.采购单是新建或已分配才领取
        Date date = new Date();
        List<PurchaseEntity> purchaseEntities = ids.stream().map(i -> {
                    PurchaseEntity purchaseEntity = getById(i);
                    return purchaseEntity;
                }).filter(i -> i.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(i->{
                    i.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    i.setUpdateTime(date);
                    return i;
                }).collect(Collectors.toList());
        //2.改变采购单状态
        updateBatchById(purchaseEntities);
        //3.改变采购项状态
        purchaseEntities.forEach(i->{
            List<PurchaseDetailEntity> list =  purchaseDetailService.listDetailByPurchaseId(i.getId());
            List<PurchaseDetailEntity> list1 = list.stream().map(j -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(j.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(list1);
        });
    }
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {

        //2.改变采购项状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item: items ) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.成功采购的入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);
        //1.改变采购单状态
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        if(flag){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else{
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        updateById(purchaseEntity);


    }

}
